<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<div>
			<!-- 标签 -->
   		 <!-- Nav tabs 标签导航-->
    <ul class="nav nav-tabs" role="tablist">
      <li role="presentation" class="active"><a href="#roleList" id="getRolefind" aria-controls="roleList" role="tab" data-toggle="tab">角色列表</a></li>
      <li role="presentation"><a href="#roleAdd" id="getRoleAdd" aria-controls="roleAdd" role="tab" data-toggle="tab">角色添加</a></li>
    </ul>
      
    	  <!-- 标签的内容 -->
   		<!-- Tab panes 选项卡窗格-->
    <div class="tab-content">
			<!-- 此处的id对应标签中的a的href链接 -->
	    	<div role="tabpanel" class="tab-pane active" id="roleList">
	    		<div id="toolbar" class="btn-group">
	      			  	<button id="btn_add_role" type="button" class="btn btn-default">
							<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>增加
						</button>
						<button id="btn_update_role" type="button" class="btn btn-default">
							<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
						</button>
						<button id="btn_delete_role" type="button" class="btn btn-default">
							<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
						</button>
				</div>
		   		<div id="roleSelect"></div>
	   		</div>
      		<div role="tabpanel" class="tab-pane" id="roleAdd"></div>
			<div role="tabpanel" class="tab-pane" id="roleUpdate"></div>
 	</div>
</div>

<!-- 模态框() -->
<div class="modal fade" id="roleupdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel"><font color='blue'>角色修改</font></h4>
            </div>
            <div class="modal-body">
            	<div id="prot1" style="height:360px;">
            		<div class="col-md-12 col-sm-12 col-xs-12 text-center">
            			<form id="roleUpdateForm" class="form-horizontal">
            				<div class="col-md-12 col-sm-12 col-xs-12 mar">
								<div class="form-group">
									<div class="input-group">
										<span class="input-group-addon">角色名称</span><input class="form-control" name="name" type="text"><input class="form-control" name="id" type="hidden">
										<input class="form-control" name="updateDate" type="hidden">
									</div>
								</div>
							</div>
							<div class="col-md-12 col-sm-12 col-xs-12 mar">
								<div class="form-group">
									<div class="input-group">
										<span class="input-group-addon">英文名称</span><input class="form-control" name="eName" type="text">
									</div>
								</div>
							</div>
							<div class="col-md-12 col-sm-12 col-xs-12 mar">
								<div class="form-group">
									<div class="input-group">
										<span class="input-group-addon">角色授权</span><input type="hidden" name="authIds" id="authIds2" value="" /><ul id="treeAuths2" class="ztree"></ul>
									</div>
								</div>
							</div>
							<div class="col-md-12 col-sm-12 col-xs-12 mar">
								<div class="form-group">
									<div class="input-group">
										<span class="input-group-addon">备注</span><textarea class="form-control" cols="40" rows="3" name="remarks"></textarea>
									</div>
								</div>
							</div>
						</form>	
					</div>	
        		</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                	<button type="button" class="btn btn-primary" id ="updateRoleBtn">确定</button>
               	</div>
        	</div> 
		</div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
<!-- end() -->
<script type="text/javascript">
function jsonDateFormat(jsonDate) {//json日期格式(毫秒)转换为date格式
    try {
        var date  = new Date(jsonDate);
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day   = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hour  = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var min   = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var sec   = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return date.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
    } catch (ex) {
        return "";
    }
}  

/* bootstrap 验证表单是否为空 */
function formValidator() {
	$("#roleUpdateForm").bootstrapValidator({
		live : 'enabled',//验证时机，enabled是内容有变化就验证（默认），disabled和submitted是提交再验证
		excluded : [ ':disabled', ':hidden', ':not(:visible)' ],//排除无需验证的控件，比如被禁用的或者被隐藏的
		message : '通用的验证失败消息',//好像从来没出现过
		feedbackIcons : {//根据验证结果显示的各种图标
			valid : 'glyphicon glyphicon-ok',
			invalid : 'glyphicon glyphicon-remove',
			validating : 'glyphicon glyphicon-refresh'
		},
		fields : {
			name: {//验证input项：验证规则
                message: '角色名',
                validators: {
                    notEmpty: {//非空验证：提示消息
                        message: '角色名不能为空'
                    },
                    stringLength: {
                        min: 1,
                        max: 10,
                        message: '角色名长度必须在1到10之间'
                    },
                    threshold :  3 , //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
                    remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}  
                        url: 'role/checkUpdateName',//验证
                        message: '角色名已存在',//提示消息
                        delay :  2000,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
                        type: 'POST',//请求方式
                        data: function(validator) {
                        	return {
                        		id:$("#roleUpdateForm input[name=id]").val(),
                        		name:$("#roleUpdateForm input[name=name]").val()
                        	};
                        }
                    }
                }
            },
			eName: {
			validators : {
				notEmpty : {
					message : '文本框必须输入'
				}
			}
		  }
		}
	});
}


//页面加载完就执行
$(function(){
	loadPage("page/roleSelect", "#roleSelect"); //向 Id = roleSelect的div嵌入页面roleSelect.jsp
	loadPage("page/roleAdd", "#roleAdd");   //向 Id = roleAdd的div嵌入页面roleAdd.jsp
});

$("#btn_add_role").click(function(){
	$('#getRoleAdd').click();
});	 

//准备修改角色
$("#btn_update_role").click(function(){
	if(getRow == null) {
		alert("请选择角色");
	}else {
			$.ajax({
				url:'menu/roleHasMenu',	
				type:'post',
				dataType:'json',
				data:{'roleId':getRow.id},
				success:function(data){
					if(data.status==200){
						var menu = data.result;
						console.log(menu);
						$.fn.zTree.init($("#treeAuths2"), setting, menu);
					}
				}
			});
		$("#roleUpdateForm input[name=id]").val(getRow.id);
		$("#roleUpdateForm input[name=updateDate]").val(jsonDateFormat(getRow.updateDate));
		$("#roleUpdateForm input[name=name]").val(getRow.name);
		$("#roleUpdateForm input[name=eName]").val(getRow.eName);
		$("#roleUpdateForm input[name=remarks]").val(getRow.remarks);
		$("#roleupdateModal").modal('show');
		formValidator();
	}
});

//开始修改角色
$('#updateRoleBtn').click(function(){
	var treeObj = $.fn.zTree.getZTreeObj("treeAuths2");  //1. 获取 id 为 menuTree 的 zTree 对象
	var nodes = treeObj.getCheckedNodes(true);//在提交表单之前将选中的checkbox的Id收集
	var array = new Array();
	for(var i=0; i<nodes.length; i++){
		array.push(nodes[i].id);
	}
	var authIds = array.join(",");   //拼接成被选中的checkbox的Id字符串
	$("#roleUpdateForm input[name='authIds']").val(authIds); //将这种id字符串赋值给name=authId的input（隐藏域）
	$("#UpdateUserform").bootstrapValidator('validate'); //提交验证  
	if($("#roleUpdateForm").data("bootstrapValidator").isValid()) {
			$.ajax({
				url:'role/update',	
				type:'post',
				dataType:'json',
				data:$("#roleUpdateForm").serialize(),
				success:function(data){
					if(data.status==200){
						alert("ok");
						getRow = null;
						loadPage("page/roleSelect", "#roleSelect");
					}
				},
				error:function(data) {
					console.log(data.msg);
				}
			});
			$("#roleupdateModal").modal('hide');
			$("#roleUpdateForm")[0].reset();
		}
});

$("#btn_delete_role").click(function(){
	if(getRow == null) {
		alert("请选择角色");
	}else {
		$.ajax({
			url:'role/del',
			type:'post',
			dataType:'json',
			data:{'id':getRow.id,'updateDate':jsonDateFormat(getRow.updateDate)},
			success: function(data) {
				if(data.status==200) {
					alert(data.msg);
				}
				getRow = null;
				loadPage("page/roleSelect", "#roleSelect");
			},
			error: function(data) {
				console.log(data.msg);
			}
		});
	}
});
</script>
	
</html>